IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'spPressreleasesUpdateMessageAndTypeId') AND type in (N'P', N'PC'))
	DROP PROCEDURE spPressreleasesUpdateMessageAndTypeId
GO
-- =============================================
-- Author:	Nam Tran
-- Create date: Sep 4, 2014
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[spPressreleasesUpdateMessageAndTypeId]
	@Date DATETIME,
	@DateNumberic BIGINT,
	@SourceCode VARCHAR(50),
	@LangId INT,
	@Message NVARCHAR(MAX),
	@Title NVARCHAR(500),	
	@SourceId INT,
	@MessageTypeID INT
AS
BEGIN
	DECLARE @PressreleasesId BIGINT = -1

	-- Try to find existing pressrelease which has same Title and Date
	SET @PressreleasesId = (SELECT TOP 1 Id FROM Pressreleases 
							WHERE Title = @Title 
								AND DateNumeric = @DateNumberic 
								AND SourceId = @SourceId 
								AND SourceCode = @SourceCode
								AND LangId = @LangId)

	-- If pressrelease is already existing, just update fileds: "MessageTypeID" and "Message"
	IF(@PressreleasesId IS NOT NULL AND @PressreleasesId > 0)
	BEGIN
		IF (@MessageTypeID IS NOT NULL)
			UPDATE Pressreleases SET MessageTypeId = @MessageTypeID WHERE Id = @PressreleasesId AND MessageTypeId IS NULL
		IF(@Message IS NOT NULL)
			UPDATE Pressreleases SET [Message] = @Message WHERE Id = @PressreleasesId
	END
	ELSE
	BEGIN
		SET @PressreleasesId = CAST(-1 AS BIGINT)
	END
		
	SELECT @PressreleasesId
END